/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { App, ComputedRef } from 'vue';

function showPopover($event: Event, binding: Record<string, any>, reference: any) {
    $event.stopPropagation();
    const popoverInstance = binding.value as ComputedRef;
    if (popoverInstance && popoverInstance.value) {
        popoverInstance.value.show(reference);
    }
}

function hidePopover($event: Event, binding: Record<string, any>) {
    $event.stopPropagation();
    const popoverInstance = binding.value as ComputedRef;
    popoverInstance.value.hide();
}

const popoverDirective = {
    mounted: (element: any, binding: Record<string, any>, vnode: any) => {
        let app: App | null;
        if (binding.modifiers.hover) {
            element.addEventListener('mouseenter', ($event: MouseEvent) => showPopover($event, binding, element));
            element.addEventListener('mouseleave', ($event: MouseEvent) => hidePopover($event, binding));
        } else if (binding.modifiers.click) {
            element.addEventListener('click', ($event: Event) => showPopover($event, binding, element));
        } else {
            element.addEventListener('click', ($event: Event) => showPopover($event, binding, element));

            // element.addEventListener('mouseenter', ($event: MouseEvent) => showPopover($event, binding, element));
            // element.addEventListener('mouseleave', ($event: MouseEvent) => hidePopover($event, binding));
        }
    },
    unMounted: (element: any, binding: Record<string, any>, vnode: any) => { }
};
export default popoverDirective;
